<!-- 3D生产进度监控查询  productsche -->
<template>
  <div class="productSche-container">
    <div class="production-schedule">
      <div class="schedule-title">
        <div class="left">
          <div class="title">
            <div class="title-decorator"></div>
            <div class="title-text">3D生产进度监控查询</div>
          </div>
        </div>
        <div class="right">
          <Select v-model="standardId" @on-change="selectChange" style="width:200px" v-if="proProcessList.length > 0">
              <Option v-for="item in proProcessList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </div>
      </div>
      <div class="schedule-container">
        <Steps :current="currentProduction" v-if="productInfo.length">
            <Step v-for="(item, idx) in productInfo" :key="idx" :title="item.proName" @click.native="processesClick(item)"></Step>
        </Steps>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Tcmd } from './command'
import { Component, Prop, Vue } from 'vue-property-decorator';
import { getBroadcastInstance } from './broadcastUtils';
import * as echarts from 'echarts';
import { Tsrv, ts } from '@/services';

interface production {
  id: string;
  // 顺序号  sequence_num
  sequence: number;
  // 工序编码 proca_id
  proId: string;
  // 工序名称 pro_name
  proName: string;
  // 工序状态 f_status
  status: number;
}

// 根据地址路径中 产线id 返回数据的类型
type proResultType = 'eq' | 'ty' | '';

interface eqInfo {
  // 设备ID
  id: string;
  // 设备名称
  name: string;
  // 设备序号
  sequence: number;
}

interface tyInfo {
  // 典规ID
  // eslint-disable-next-line camelcase
  typical_pro_id: string;
  // 典规名称
  FName: string;
}

// 根据地址路径中 产线id 返回数据 data 格式
interface proResultData {
  cmd: proResultType;
  info: eqInfo[] | tyInfo[];
}


@Component  
export default class ProductSche extends Vue {
  @Prop() readonly fworkId!: string;

  private broadcastChannel = getBroadcastInstance('PRODUCTION_PROCESSES_CHANGE');

  private currentProduction: number = 0;

  /**
   * 典规ID值
   */
  private standardId: string = '-1';

  // 工序信息表名（即流程）
  private tableName: string = 'process_name_info'

  /**
   * 设备限制 表名
   */
  private deviceTable: string = 'equip_tabile'

  /**
   * 工序信息 类型：eq:设备  ty:典规
   */
  private processesType: proResultType = '';

  private productInfo: production[] = []

  /**
   * 工序信息 ———— 即：流程图数据Array
   */
  private proProcessList:Array<any> = []

  private productionLineId = '447986112338599936';

  private productionLine: Array<string> = [
    '447986112338599936',
    '448002311529177088',
    '458821616369934336',
    '487900900694695936'
  ];

  create() {}

  mounted() {
    this.productionLineId = Tsrv.utils.clone(this.fworkId)
    this.getProductionLine().then(res=> {
      if (res && this.processesType === 'ty') {
        this.getProcessInfo();
      }
    })

    // 添加消息监听
    this.broadcastChannel.addMessageHandler(this.handleBroadcastMessage);
  }

  // 消息处理函数
  private handleBroadcastMessage(data: any) {
    // console.log(`更新`);
  }

  /**
   * @description 获取生产产线 信息
   * @description 1、该产线下 共有几条 典规数据
   * @description 2、
   */
  private getProductionLine(): Promise<boolean> {
    return new Promise((resolve, reject)=> {
      if (Tsrv.noValue(this.fworkId)) {
        this.$Message.error('未找到产线ID');
        resolve(false)
        return;
      }
      const param = {
        type: 'svcLogic',
        cmd: 'GetTypicalProId',
        userInfo: {},
        funInfo: {},
        data: {
          fworkId: this.fworkId
        }
      }

      Tcmd.doEvent(param).then(res=> {
        const [b, resp, data, msg] = res;
        if (b) {
          // console.log('典规信息', data);
          const d = data?.data;
          if (!Tsrv.noValue(d)) {
            const cmd = d?.cmd as proResultType;
            this.processesType = cmd;
            const info = d?.info;
            if (Tsrv.noValue(info) || !Array.isArray(info)) {
              this.$Message.error('info数据为空或不合法');
              resolve(false)
            }
            if (cmd === 'eq') {
              const productInfo: production[] = [];
              for (let i = 0; i < info.length; i++) {
                const el = info[i];
                const pro: production = {
                  id: el['id'],
                  sequence: el['seq'],
                  proId: '',
                  proName: el['name'],
                  status: 0
                }
                productInfo.push(pro);
              }
              this.productInfo = productInfo.sort((a: any, b: any) => {
                return a.sequence - b.sequence;
              });
              // 档切换产线流时 发第一个槽信息
              const param = {
                id: productInfo[0].id
              }
              this.processesClick(param)
              resolve(true)
            } else if (cmd === 'ty') {
              this.standardId = info[0]['typical_pro_id'];
              this.proProcessList = info.map((item: any)=> {
                return {
                  value: item['typical_pro_id'],
                  label: item['FName']
                }
              })
            } else {
              this.$Message.error('cmd不合法！');
              resolve(false)
            }
          } else {
            this.$Message.error('data数据为空');
            resolve(false)
          }
        }
      }).catch(err=> {
        this.$Message.error(`未找到产线，请确保当前产线存在——${err}`);
      });
    })
  }

  /**
   * 获取工序 信息
   * 根据 典规ID 获取工序信息
   */
  private getProcessInfo(): Promise<boolean> {
    return new Promise((resolve, reject)=> {
      const fliter = new ts.T_filter();
      // f_status
      fliter.filter = { $and : [{ master_bill_id: { $eq: this.standardId } }, { f_status: { $in: [1] } }] }

      Tcmd.getTableData(this.tableName, fliter).then(([b, res, rows, msg])=> {
          if (b) {
            if (rows.length > 0) {
              const productInfo: production[] = [];
              for (let i = 0; i < rows.length; i++) {
                const el = rows[i];
                const pro: production = {
                  id: el.id,
                  sequence: el.sequence_num,
                  proId: el.proca_id,
                  proName: el.pro_name,
                  status: el.f_status
                }
                productInfo.push(pro);
              }
              this.productInfo = productInfo.sort((a: any, b: any) => {
                return a.sequence - b.sequence;
              });
              // 档切换产线流时 发第一个槽信息
              const param = {
                id: productInfo[0].id
              }
              this.processesClick(param)
              resolve(true)
            }
          } else {
            this.$Message.error(msg);
            resolve(false)
          }
        }).catch(err=> {})
    })
  }

  private processesClick(item: any) {
    // console.log('触发', item);
    // 广播状态变更
    const data = {
      type: 'production_processes_change',
      data: {
        fworkId: this.fworkId,
        standardId: this.standardId,
        processId: '',
        deviceId: ''
      }
    }
    if (this.processesType === 'eq') {
      data.data.deviceId = item.id;
      this.broadcastChannel.postMessage(data);
    } else if (this.processesType === 'ty') {
      data.data.processId = item.id
      this.getDeviceData(item.id).then((deviceId: string)=> {
        data.data.deviceId = deviceId;
        this.broadcastChannel.postMessage(data);
        // console.log('发送方', data);
      }).catch(err=> {
        this.broadcastChannel.postMessage(data);
        // console.log('发送方', data);
      });
    }

    this.getDeviceData(item.id).then((deviceId: string)=> {
      data.data.deviceId = deviceId;
      this.broadcastChannel.postMessage(data);
      // console.log('发送方', data);
    }).catch(err=> {
      this.broadcastChannel.postMessage(data);
      // console.log('发送方', data);
    });
  }

  /**
   * 获取指定工序的设备信息
   * @param processId 
   * @returns 
   */
  private getDeviceData(processId: string): Promise<any> {
    return new Promise((resolve, reject)=> {
      const fliter = new ts.T_filter();
      fliter.filter = { $and : [{ master_bill_id: { $eq: processId } }] }
      Tcmd.getTableData(this.deviceTable, fliter.filter).then(([b, res, rows, msg])=> {
        if (b) {
          if (rows.length > 0) {
            resolve(rows[0]['id'])
          } else {
            resolve('')
          }
        } else {
          this.$Message.error(msg);
          resolve('')
        }
      })
    })
  }


  /**
   * 获取当前生产进度
   */
  private getCurrentProduction() {
    this.currentProduction = 6;
  }

  private selectChange(e: any) {
    this.standardId = e;
    this.getProcessInfo();
  }

  beforeDestroy() {
    // 清理监听
    this.broadcastChannel.removeMessageHandler(this.handleBroadcastMessage);
  }
}
</script>

<style lang="scss" scoped>
.productSche-container {
  width: 100%;
  height: 100%;
  .production-schedule {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .schedule-title {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      width: 100%;
      padding: 0 50px 0;
      border-bottom: 1px solid rgba(4, 231, 251, 0.8);

      .left {
        display: flex;
        flex-direction: row;
        align-items: center;

        .title {
          display: flex;
          flex-direction: row;
          justify-content: start;
          align-items: center;

          .title-decorator {
            width: 5px;
            height: 20px;
            background-color: #04E7FB;
          }
          .title-text {
            margin-left: 10px;
            font-size: 16px;
            color: #fff ;
          }
        }
      }

      ::v-deep .right {
        .ivu-select {
          .ivu-select-selection {
            background: transparent;
            color: #fff;
          }
        }
      }
    }

    ::v-deep .schedule-container {
      flex: 1;
      height: 100%;
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 0 100px 0;

      .ivu-steps {
        .ivu-steps-item {
          .ivu-steps-head {
            background: transparent;
          }
          .ivu-steps-main {
            .ivu-steps-title {
              background: rgb(8, 45, 50);
              border-radius: 3px;
              padding-left: 2px;
              color: #04E7FB !important;
              border: 1px solid #04E7FB;
            }
          }
          .ivu-steps-head-inner {
            border-color: #04E7FB;
            background-color: #04E7FB;
            .ivu-steps-icon {
              color: #fff;
            }
            span {
              color: #fff;
            }
          }
        }
        // .ivu-steps-item {
        //   .ivu-steps-head {
        //     background: transparent;
        //   }
        //   .ivu-steps-main {
        //     .ivu-steps-title {
        //       background: rgb(8, 45, 50);
        //       border-radius: 3px;
        //       padding-left: 2px;
        //     }
        //   }
        //   &.ivu-steps-status-finish {
        //     .ivu-steps-main {
        //       .ivu-steps-title {
        //         color: #04E7FB !important;
        //         border: 1px solid #04E7FB;
        //       }
        //     }
        //     .ivu-steps-head-inner {
        //       border-color: #04E7FB;
        //       background-color: #04E7FB;
        //       .ivu-steps-icon {
        //         color: #fff;
        //       }
        //     }
        //   }
        //   &.ivu-steps-status-process {
        //     .ivu-steps-main {
        //       .ivu-steps-title {
        //         color: rgb(236, 176, 68) !important;
        //         border: 1px solid rgb(236, 176, 68);
        //       }
        //     }
        //     .ivu-steps-head-inner {
        //       border-color: rgb(236, 176, 68);
        //       background-color: rgb(236, 176, 68);
        //       .ivu-steps-icon {
        //         color: #fff;
        //       }
        //     }
        //   }
        //   &.ivu-steps-status-wait {
        //     .ivu-steps-main {
        //       .ivu-steps-title {
        //         color: #ccc !important;
        //         border: 1px solid #ccc;
        //       }
        //     }
        //   }
        // }
      }
    }
  }                                     
}
</style>